package com.wx.controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.wx.cache.SyncMap;
import com.wx.commons.SyncFansThread;
import com.wx.core.process.WxApi;
import com.wx.core.vo.FansChangeGroup;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxFansGroup;
import com.wx.entity.WxFansUser;
import com.wx.entity.WxFansUserExample;
import com.wx.entity.WxFansUserExample.Criteria;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxFansGroupService;
import com.wx.service.WxFansUserService;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.wx.vo.WxFansUserResult;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.util.HttpUtils;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;

/**
 * 
 * @ClassName: WxFansController
 * @Description: 对粉丝的管理
 * @author yinkx
 * @date 2015年7月29日 上午11:47:34
 *
 */
@Controller
@RequestMapping("admin/fansUser")
public class WxFansController extends AbsManageBaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Value("#{propertiesReader[session_user_key]}")
	private String sessionKey;
	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;
	@Resource
	private WxFansUserService wxFansUserService;
	@Resource
	private WxFansGroupService WxFansGroupService;
	@Resource
	private SysWxTokenService sysWxTokenService;
	@Resource
	private SysWxuserService sysWxuserService;

	// 获取acctoken
	@RequestMapping
	protected final String getAccessToken(HttpServletRequest request, HttpSession session) {
		SysWxuser wxuser = getSessionWxUser(request);
		String wxid = getWxId(request);
		String appId = wxuser.getAppid();
		String appSecret = wxuser.getAppsecretd();
		String accessToken = sysWxTokenService.getAccessToken(wxid, appId, appSecret);
		return accessToken;
	}

	@RequestMapping("index")
	public String list(@RequestParam(value = "currentPage", required = false) String currentPage,
			HttpServletRequest request, @RequestParam(value = "keyword", required = false) String keyword,
			@RequestParam(value = "subscribe", required = false) String subscribe,
			@RequestParam(value = "wechatgroupid", required = false) String wechatgroupid) {
		if (currentPage == null)
			currentPage = "1";
		// 微信列表过来的
		if (!StringUtils.isEmpty(request.getParameter("wxid"))) {
			String wxid = request.getParameter("wxid");
			SysWxuser wxuser = sysWxuserService.selectByWxid(wxid);
			request.getSession().setAttribute(session_wx_key, wxuser);
		}
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.parseInt(pageSizeStr);
		String wxid = getWxId(request);
		//测试用的wxid
		WxFansUserExample example = new WxFansUserExample();
		Criteria cr = example.createCriteria().andSubscribeEqualTo(1);
		cr.andWxidEqualTo(wxid);
		if (keyword != null && !keyword.equals(""))
			cr.andNicknameLike("%" + keyword + "%");
		if (wechatgroupid != null && !wechatgroupid.equals(""))
			cr.andGroupidEqualTo(Integer.valueOf(wechatgroupid));
		if (subscribe != null && !subscribe.equals(""))
			cr.andSubscribeEqualTo(Integer.parseInt(subscribe));
		//cr.andSubscribeLike(Integer.parseInt(subscribe));

		List<WxFansUserResult> relist = new ArrayList<WxFansUserResult>();
		// 查询所有组名
		List<WxFansGroup> grouList = WxFansGroupService.selectByWxid(wxid);

		int count = wxFansUserService.countByExample(example);
		if (count > 0) {
			Page<WxFansUser> page = new Page<WxFansUser>(count, Integer.valueOf(currentPage), pageSize);
			example.setLimit(pageSize);
			example.setStart(page.getStart());
			example.setOrderByClause("subscribe_time desc");
			List<WxFansUser> list = wxFansUserService.selectByExample(example);
			for (WxFansUser fansUser : list) {// 转换名称
				WxFansUserResult fu = new WxFansUserResult();
				BeanUtils.copyProperties(fansUser, fu);
				if (grouList.size() > 0) {
					for (WxFansGroup wxFansGroup : grouList) {// 转换名称
						if (fu.getGroupid() != null
								&& fu.getGroupid().intValue() == wxFansGroup.getGroupId().intValue())
							fu.setGroupidStr(wxFansGroup.getName());
						else
							continue;
					}
				}
				relist.add(fu);
			}
		}
		Page<WxFansUserResult> pageResult = new Page<WxFansUserResult>(count, Integer.valueOf(currentPage), pageSize);
		pageResult.setRecordList(relist);
		request.setAttribute("page", pageResult);
		request.setAttribute("relist", relist);
		request.setAttribute("grouList", grouList);
		request.setAttribute("keyword", keyword);
		request.setAttribute("subscribe", subscribe);
		request.setAttribute("wechatgroupid", wechatgroupid);
		return "crm/fans";
	}

	@RequestMapping("tolist")
	public String tolist(Model model) {
		model.addAttribute("msg", "列表更新完毕");
		model.addAttribute("redirect", "admin/fansUser/index");
		return "message";
	}

	@RequestMapping(value = "/syncCount", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	public @ResponseBody String syncCount(HttpServletRequest request) {
		String threadName = "syncFans_" + getSessionUser(request).getId();
		SyncFansThread syn = SyncMap.fanMap.get(threadName);
		if (syn != null && syn.isAlive()) {
			HashMap<String, Integer> map = new HashMap<String, Integer>();
			map.put("total", syn.getTotal());
			map.put("count", syn.getCount());
			return JsonUtil.Object2Json(JsonResult.objectJson(map));
		} else {
			return JsonUtil.Object2Json(JsonResult.messageJson(false, ""));
		}
	}

	@RequestMapping("toUpdate")
	public String toUpdate(Model model, HttpServletRequest request) {
		String threadName = "syncFans_" + getSessionUser(request).getId();
		SyncFansThread syn = SyncMap.fanMap.get(threadName);
		if (syn == null || !syn.isAlive()) {
			syn = new SyncFansThread();
			syn.setName(threadName);
			SysWxuser sysWxuser = getSessionWxUser(request);
			SysUser session_user = getSessionUser(request);
			String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(), sysWxuser.getAppid(),
					sysWxuser.getAppsecretd());
			if (StringUtils.isEmpty(accessToken)) {
				model.addAttribute("msg", "公众丢失授权绑定");
				model.addAttribute("redirect", "admin/sysuser/list");
				return "message";
			}
			syn.setAccessToken(accessToken);
			syn.setSysWxuserService(sysWxuserService);
			syn.setUid(session_user.getId());
			syn.setWxFansUserService(wxFansUserService);
			syn.setWxid(sysWxuser.getWxid());
			syn.start();
			SyncMap.fanMap.put(threadName, syn);
		}
		return "fansmeg";
	}

	@RequestMapping(value = "change", method = RequestMethod.GET)
	public String change(@RequestParam(value = "idStr", required = true) String idStr,
			@RequestParam(value = "currentPage", required = false) String currentPage,
			@RequestParam(value = "keyword", required = false) String keyword,
			@RequestParam(value = "groupid1", required = false) String groupid1,
			@RequestParam(value = "groupid2", required = false) String groupid2, HttpServletRequest request,
			Model model) {
		String[] ids = idStr.split(",");
		ArrayList<String> openlist = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++) {
			WxFansUser fansUser = wxFansUserService.selectByPrimaryKey(Integer.valueOf(ids[i]));
			fansUser.setGroupid(Integer.valueOf(groupid2));
			wxFansUserService.updateByPrimaryKey(fansUser);
			openlist.add(fansUser.getOpenid());
		}
		// 移动用户分组 同步至微信平台
		SysWxuser sysWxuser = getSessionWxUser(request);
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(), sysWxuser.getAppid(),
				sysWxuser.getAppsecretd());
		if (StringUtils.isEmpty(accessToken)) {
			model.addAttribute("msg", "公众丢失授权绑定");
			model.addAttribute("redirect", "admin/sysuser/list");
			return "message";
		}
		Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
		String wxjson = gson.toJson(new FansChangeGroup(openlist, Integer.valueOf(groupid2)));
		logger.debug("****改变分组JSON*******" + wxjson);
		String requestUrl = WxApi.getRequestUrl(WxApi.GROUP_BATCH_UPDATE, accessToken);
		String result = HttpUtils.httpsPost(requestUrl,wxjson);
		JSONObject jSONObject = JSONObject.parseObject(result);
		logger.debug("****返回结果*******" + jSONObject.toString());
		model.addAttribute("keyword", keyword);
		model.addAttribute("wechatgroupid", groupid1);
		model.addAttribute("msg", "设置完毕");
		model.addAttribute("redirect", "admin/fansUser/index");
		return "message";
	}

	public WxFansUser JsonToWxFansUser(String json) {
		Gson gsonUp = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
			@Override
			public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
					throws JsonParseException {
				return new Date(json.getAsJsonPrimitive().getAsLong());
			}
		}).create();
		return gsonUp.fromJson(json, WxFansUser.class);
	}

}
